<?php

class cash_obj {

    public function getCashMoveType() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_cash_move'] . " ORDER BY id";
        return $db_obj->getAll($sql);
    }
    
    public function getCashMoveTypeById($id){
        $id = (int) $id;
        if (empty($id))
            return new error_obj ('empty id', __CLASS__, __FUNCTION__);
        
        $db_obj = new db_obj();
        
        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_cash_move'] . " WHERE Id='".$id."'";
        
        return $db_obj->getRow($sql);
    }

    public function checkAdd_entry($check_data) {
        $result = array();
        foreach ($check_data as $key => $value) {
            switch ($key) {
                case 'amount':
                    $value = (double) $value;
                    if (!is_double($value) || ($value<=0) )
                        $result[] = 'amount';
                    break;
                case 'date':
                    if (empty($value))
                        $result[] = 'date';
                    break;
                case 'description':
                    if (empty($value))
                        $result[] = 'description';
                    break;
            }
        }
        return $result;
    }
    
    public function addEntry($in_data) {
        if (empty($in_data)) {
            return new error_obj('empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $result = $db_obj->insert($GLOBALS['tb_cash'], $in_data);
        if (error_obj::isError($result))
            return $result;
        else
            return $db_obj->lastInsertedId();
    }
    
    public function getListOfCashes($filter = array(), $order = array(), $limit = '', $what = '*') {
        $db_obj = new db_obj();
        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)){
            if (!empty($order['table'])){
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' .  $order['orderBy'] . ' ' . $order['order'];
                $connector = 'AND ' . $GLOBALS['tb_cash'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'];
            }
        }
        if ($limit != '')
            $limit = ' LIMIT ' . $limit;
        if (strpos($what, 'COUNT') === false){
            $what = $GLOBALS['tb_cash'] . '.' . $what;
        }

        $where = 'WHERE 1=1';

        foreach ($filter as $key => $value) {
            if ($key=='period'){
                $period = explode('/', $value);
                $m = (int) $period[0];
                $y = (int) $period[1];
                $where .= " AND DATE_FORMAT(date, '%c')='" . $m . "' AND DATE_FORMAT(date, '%Y')='" . $y . "'";
            } else    
                $where .= " AND " . $key . "='" . $value . "'";
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_cash'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug('getListOfCashes sql', $sql);

        return $db_obj->getAll($sql);
    }

    public function getListOfCashesByFulltext($fulltext, $filter = array(), $order = array(), $limit = '', $what = '*') {
        $where = '';
        $db_obj = new db_obj();

        if (!empty($fulltext)) {
            $fulltext = strip_tags(trim($fulltext));

            $fulltext = explode(" ", $fulltext);
            $fulltextResults = array();
            foreach ($fulltext as $key => $word) {
                $sql = "SELECT " . $GLOBALS['tb_cash'] . ".Id 
                    FROM " . $GLOBALS['tb_cash'] . ",
                         " . $GLOBALS['tb_type_of_cash_move'] . ",
                         " . $GLOBALS['tb_users'] . "   
                    WHERE 
                    " . $GLOBALS['tb_cash'] . ".type_of_move = " . $GLOBALS['tb_type_of_cash_move'] . ".Id AND (
                    " . $GLOBALS['tb_cash'] . ".who_added = " . $GLOBALS['tb_users'] . ".users_id OR    
                    " . $GLOBALS['tb_cash'] . ".user = " . $GLOBALS['tb_users'] . ".users_id ) AND (
                    " . $GLOBALS['tb_cash'] . ".description LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".name LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".surname LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_type_of_cash_move'] . ".TypPohybu LIKE '%" . $word . "%' 
                    )";
                $fulltextResults[] = array_unique($db_obj->getCol($sql));
            }
            if (isset($fulltextResults[0]) && !empty($fulltextResults[0])) {
                $temp = $fulltextResults[0];
                foreach ($fulltextResults as $key => $array) {
                    $temp = array_intersect($temp, $array);
                }
                if (!empty($temp)) {
                    $where .= 'WHERE (';
                    foreach ($temp as $id) {
                        $where .= "Id='" . $id . "' OR ";
                    }
                    $where = substr($where, 0, $length - 4);
                    $where .= ')';
                } else {
                    $where .= 'WHERE 1=2';
                }
            } else {
                $where .= 'WHERE 1=2';
            }
        } else {
            $where .= 'WHERE 1=1';
        }

        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)){
            if (!empty($order['table'])){
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' .  $order['orderBy'] . ' ' . $order['order'];
                $connector = 'AND ' . $GLOBALS['tb_cash'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'];
            }
        }
        if ($limit != '')
            $limit = ' LIMIT ' . $limit;
        if (strpos($what, 'COUNT') === false){
            $what = $GLOBALS['tb_cash'] . '.' . $what;
        }

        foreach ($filter as $key => $value) {
            if ($key=='period'){
                $period = explode('/', $value);
                $m = (int) $period[0];
                $y = (int) $period[1];
                $where .= " AND DATE_FORMAT(date, '%c')='" . $m . "' AND DATE_FORMAT(date, '%Y')='" . $y . "'";
            } else 
                $where .= " AND " . $key . "='" . $value . "'";
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_cash'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug('getListOfCashes sql', $sql);

        return $db_obj->getAll($sql);
    }
    
    public function getEntry($id, $cols = array()) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('getEntry empty id', __CLASS__, __FUNCTION__);

        $what = '';
        if (!empty($cols)) {
            foreach ($cols as $value) {
                $what .= $value . ',';
            }
            $what = substr($what, 0, strlen($what) - 1);
        } else {
            $what .= '*';
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_cash'] . " WHERE Id='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function editEntry($in_data, $id) {
        $id = (int) $id;
        if (empty($id)) {
            return new error_obj('empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $keys = array('Id' => $id);
        return $db_obj->update($GLOBALS['tb_cash'], $in_data, $keys);
    }
    
    public function getEntryByTransfer_between($hash, $mode='<') {
        $db_obj = new db_obj();
        $id = (int) $hash;
        if (empty($id) || !is_numeric($id))
            return new error_obj('getEntry empty hash', __CLASS__, __FUNCTION__);

        $what = '';
        if (!empty($cols)) {
            foreach ($cols as $value) {
                $what .= $value . ',';
            }
            $what = substr($what, 0, strlen($what) - 1);
        } else {
            $what .= '*';
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_cash'] . " WHERE amount".$mode."0 AND transfer_between ='" . $id . "'";
        base_obj::debug('getEntryByTransfer_between sql', $sql);
        
        return $db_obj->getRow($sql);
    }
    
    public function deleteEntryById($id, $positive_amount = false) {
        $id = (int) $id;
        if (empty($id)){
            return new error_obj('deleteEntry -> empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        
        $where = "Id='".$id."'";
        if ($positive_amount)
            $where .= " AND amount>0";
        $sql = "DELETE FROM " . $GLOBALS['tb_cash'] . " WHERE $where";
        
        $result = $db_obj->query($sql);
        return $result;
    }
    
    public function getCountToDate($date, $user = null, $included_date = true) {
        $db_obj = new db_obj();
        
        $operation = "<=";
        if (!$included_date)
            $operation = "<";
        
        $user_sql = "";
        if (!empty($user))
            $user_sql .= " AND user='$user'";
        
        $sql = "SELECT SUM(amount) FROM " . $GLOBALS['tb_cash'] . " WHERE `date`$operation'" . $date . "'" . $user_sql;
        
        return round($db_obj->getOne($sql),2);
    }
}

?>
